package ecode

import (
	"context"
	"fmt"
	"github.com/pkg/errors"
	"inventory/pkg/env"
	"inventory/pkg/log"
	"inventory/pkg/request_key"
	"inventory/pkg/wechat"
)

// AsyncFailOver
func AsyncFailOver(ctx context.Context, serviceName string, envType env.Type, errAddr *error) {
	var errInfo string
	if r := recover(); r != nil {
		errInfo = GetPanicTrace("async", r)
	} else if errAddr != nil && *errAddr != nil {
		switch v := errors.Cause(*errAddr).(type) {
		case *ErrorCode:
			errInfo = fmt.Sprintf("async process %s error: %d-%s-%s", serviceName, v.Code(), v.CodeMessage, v.ErrMessage)
		case *WithStackModel:
			errInfo = fmt.Sprintf("async process %s error: %+v", serviceName, *errAddr)
		default:
			// 错误未填充堆栈信息
			errInfo = fmt.Sprintf("async process %s error: %s (no stack filled)", serviceName, *errAddr)
		}
	}
	if errInfo != "" {
		log.FromContext(ctx).Error(errInfo)
		if envType != env.Local {
			wechat.AsyncSendMarkDown(
				ctx, wechat.FormatBugMessage(
					ctx, envType, serviceName, request_key.GetRequestID(ctx),
					"异步处理任务失败",
					errInfo))
		}
	}
}
